package com.weiai.wedding.service.file;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import com.weiai.wedding.app.file.handle.FileHandle;
import com.weiai.wedding.dao.file.UserFileDao;
import com.weiai.wedding.dao.file.UserFileExpDao;
import com.weiai.wedding.entity.file.UserFile;
import com.weiai.wedding.util.ConUtils;
import com.weiai.wedding.util.Pagination;
import com.weiai.wedding.util.SpringContextUtil;
import com.weiai.wedding.util.UploadDomainUtil;
import com.weiai.wedding.vo.HandleFileVO;

/**
 * 文件管理类
 */
@Component(value="userFileService")
public class UserFileService {

	@Autowired
	private UserFileDao userFileDao;
	@Autowired
	private UserFileExpDao userFileExpDao;
	@Autowired
	private UploadDomainUtil uploadDomainUtil;
	public UserFile findUserFile(String id){
		return userFileDao.findOne(id);
	}
	/**
	 * 保存文件
	 * @param userFile
	 */
	public UserFile saveUserFile(UserFile userFile){
		userFileDao.save(userFile);
		return userFile;
	}
	
	public List<UserFile> findByUserId(String userId){
		
		return userFileDao.findByUserId(userId);
	}
	
	public UserFile saveUserFile(List<FileItem> fileItems,String ip) throws Exception {
		if(fileItems==null || fileItems.size()==0)
			return null;
		UserFile userFile=getUserFile();
		userFile.setIp(ip);
		HandleFileVO handleFileVO=new HandleFileVO();
		for (FileItem item:fileItems) {
			// 如果是普通表单字段
			if (item.isFormField()) {
				String name=item.getFieldName();
				String value=item.getString("utf-8");
				if("loginName".equals(name)){
					userFile.setCreatedBy(value);
				}else if("userId".equals(name)){
					userFile.setUserId(value);
				}else if("source".equals(name)){
					userFile.setSource(value);
				}else if("number".equals(name)){
					handleFileVO.setNumber(Integer.valueOf(value));
				}else if("weight".equals(name)){
					handleFileVO.setWeight(Integer.valueOf(value));
				}else if("height".equals(name)){
					handleFileVO.setHeight(Integer.valueOf(value));
				}
					
			} else if (item.getName().length() > 0) { // 如果为文件域
				//获取文件真实名称
				String realName=item.getName();
				//生成唯一文件名称
				String beforeFileName=uuidName("init",realName);
				String afterFileName=uuidName("small",realName);
				handleFileVO.setOutputFileName(afterFileName);
				handleFileVO.setInputFileName(beforeFileName);
				userFile.setFileName(realName);
				userFile.setBeforeFileName(beforeFileName);
				userFile.setAfterFileName(afterFileName);
				
				//获取文件后缀名称
				String suffix=realName.substring(realName.lastIndexOf("."));
				Map<String,String> domainPath=uploadDomainUtil.getUploadDomainAndPath(suffix);
				String domain=domainPath.get("domain");
				String path=domainPath.get("path");
				//获取上传路径
				path=getPath(path);
				userFile.setDomain(domain);
				userFile.setUploadPath(path);
				handleFileVO.setInputPath(path);
				handleFileVO.setOutputPath(path);
				File fileDir = new File(path);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				File file=new File(path, beforeFileName);
				//userFile.setFileSize(file.length());
				userFile.setDownloadUrl(userFile.getDomain()+File.separator+beforeFileName);
				userFile.setFileSuffix(suffix);
				item.write(file); // 写入文件
				//编码文件
				String type=uploadDomainUtil.getType(suffix);
				handleFileVO.setType(type);
				//如果处理文件过多，可以选择多线程处理，这里没有使用多线程
				if(StringUtils.isNotBlank(type)){
					FileHandle fileHandle = (FileHandle) SpringContextUtil.getBean(type);
					fileHandle.handleFile(handleFileVO);
				}
			}
		}
		return this.saveUserFile(userFile);
	}
	
	/**
	 * 根据用户查询条件和分页信息 返回 查询到的userFile信息
	 * @param userFile
	 * @param pager
	 * @return
	 */
	public Pagination<UserFile> findUserFileList(UserFile userFile,Pagination<UserFile> pager){
		return userFileExpDao.findUserFileList(userFile, pager);
	}
	private String getPath(String path) {
		Date date=new Date();
		return path+File.separator+ConUtils.formatDate(date, "yyyy")+ File.separator+ConUtils.formatDate(date, "MM")
		+ File.separator+ConUtils.formatDate(date, "dd")+File.separator;
	}
	private String uuidName(String code,String fileName) {
		// TODO Auto-generated method stub
		UUID uuid=UUID.randomUUID();
		return code+"_"+uuid.toString()+fileName.substring(fileName.lastIndexOf("."));
	}
	private UserFile getUserFile() {
		UserFile userFile=new UserFile();
		userFile.setCreatedTime(new Date());
		userFile.setModifyTime(new Date());
		return userFile;
	}
	
}
